package ynu.edu.item.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import ynu.edu.api.dto.ItemDTO;
import ynu.edu.api.dto.OrderDetailDTO;
import ynu.edu.common.domain.PageDTO;
import ynu.edu.common.domain.PageQuery;
import ynu.edu.common.domain.R;
import ynu.edu.common.utils.BeanUtils;
import ynu.edu.item.domain.po.Item;
import ynu.edu.item.service.IItemService;

import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "商品管理相关接口")
@RestController
@RequestMapping("/items")
@RequiredArgsConstructor
public class ItemController {

    private final IItemService itemService;

    @ApiOperation("分页查询商品")
    @GetMapping("/page")
    public R<PageDTO<ItemDTO>> queryItemByPage(PageQuery query) {
        // 1.分页查询
        Page<Item> result = itemService.page(query.toMpPage("update_time", false));
        // 2.封装并返回
        return R.ok(PageDTO.of(result, ItemDTO.class));
    }

    @ApiOperation("根据id批量查询商品")
    @GetMapping
    public R<List<ItemDTO>> queryItemByIds(@RequestParam("ids") List<Long> ids){
        return R.ok(itemService.queryItemByIds(ids));
    }

    @ApiOperation("根据id查询商品")
    @GetMapping("{id}")
    public R<ItemDTO> queryItemById(@PathVariable("id") Long id) {
        return R.ok(BeanUtils.copyBean(itemService.getById(id), ItemDTO.class));
    }

    @ApiOperation("根据商品类别查询商品")
    @GetMapping("/category/{category}")
    public R<List<ItemDTO>> queryItemsByCategory(@PathVariable("category") String category) {
        return  R.ok(itemService.queryItemsByCategory(category));
    }

    @ApiOperation("新增商品")
    @PostMapping
    public R<Boolean> saveItem(@RequestBody ItemDTO item) {
        // 新增
        return R.ok(itemService.save(BeanUtils.copyBean(item, Item.class)));
    }

    @ApiOperation("更新商品状态")
    @PutMapping("/status/{id}/{status}")
    public R<Boolean> updateItemStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status){
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        return R.ok(itemService.updateById(item));
    }

    @ApiOperation("更新商品")
    @PutMapping
    public R<Boolean> updateItem(@RequestBody ItemDTO item) {
        // 不允许修改商品状态，所以强制设置为null，更新时，就会忽略该字段
        item.setStatus(null);
        // 更新
        return R.ok(itemService.updateById(BeanUtils.copyBean(item, Item.class)));
    }

    @ApiOperation("根据id删除商品")
    @DeleteMapping("{id}")
    public R<Boolean> deleteItemById(@PathVariable("id") Long id) {
        return R.ok(itemService.removeById(id));
    }

    @ApiOperation("批量扣减库存")
    @PutMapping("/stock/deduct")
    public R<Boolean> deductStock(@RequestBody List<OrderDetailDTO> items){
        itemService.deductStock(items);
        return R.ok(true);
    }

    @ApiOperation("批量恢复库存")
    @PutMapping("/stock/restore")
    public R<Boolean> restoreStock(@RequestBody List<OrderDetailDTO> items){
        return R.ok(itemService.restoreStock(items));
    }

    @ApiOperation("根据分类分页查询商品")
    @GetMapping("/category/{category}/page")
    public R<PageDTO<ItemDTO>> queryItemsByCategory(
            @PathVariable("category") String category,
            PageQuery query) {
        // 1. 构建查询条件
        LambdaQueryWrapper<Item> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Item::getCategory, category);
        wrapper.eq(Item::getStatus, 1); // 只查询上架商品

        // 2. 分页查询
        Page<Item> result = itemService.page(query.toMpPage("update_time", false), wrapper);

        // 3. 封装并返回
        return R.ok(PageDTO.of(result, ItemDTO.class));
    }

    @ApiOperation("获取所有商品分类")
    @GetMapping("/categories")
    public R<List<String>> getAllCategories() {
        // 查询所有不重复的分类
        List<String> categories = itemService.list()
                .stream()
                .map(Item::getCategory)
                .distinct()
                .collect(Collectors.toList());

        return R.ok(categories);
    }
}
